# -*- coding: utf-8 -*-
import time
import numpy as np
from PIL import ImageGrab
import os
import requests

# 配置区
CHECK_INTERVAL = 5
INACTIVITY_THRESHOLD = 10
SCREEN_CHANGE_THRESHOLD = 200000
LOG_FILE = r"screen_activity.log"

# 服务器配置
SERVER_URL = "http://your-server-url.com/api/log"  # 替换为你后台服务器的URL
MAX_RETRIES = 3  # 最大重试次数

# 屏幕分辨率
SCREEN_WIDTH = 1920
SCREEN_HEIGHT = 1080
MONITOR_REGION = (0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 40)  # 忽略底部40像素

last_activity_time = time.time()
is_active = True

def log_status(status):
    timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
    log_entry = f"[{timestamp}] 状态: {status}\n"
    with open(LOG_FILE, "a", encoding="gb2312") as f:
        f.write(log_entry)
    print(log_entry.strip())
    
    # 将数据发送到服务器
    send_log_to_server(timestamp, status)

def send_log_to_server(timestamp, status):
    data = {
        "timestamp": timestamp,
        "status": status
    }
    headers = {
        "Content-Type": "application/json"
    }
    
    for _ in range(MAX_RETRIES):
        try:
            response = requests.post(SERVER_URL, json=data, headers=headers, timeout=5)
            if response.status_code == 200:
                print(f"成功上传到服务器: {data}")
                return
            else:
                print(f"上传失败，状态码: {response.status_code}")
        except requests.exceptions.RequestException as e:
            print(f"网络请求错误: {str(e)}")
            continue
    print("已达到最大重试次数，上传失败。")

def check_screen_change():
    global last_activity_time
    try:
        screenshot = ImageGrab.grab(bbox=MONITOR_REGION).convert("L")
        current_frame = np.array(screenshot)
        
        if not hasattr(check_screen_change, "last_frame"):
            check_screen_change.last_frame = current_frame
            return False
        
        diff = np.sum(np.abs(current_frame - check_screen_change.last_frame))
        check_screen_change.last_frame = current_frame
        
        if diff > SCREEN_CHANGE_THRESHOLD:
            last_activity_time = time.time()
            return True
        return False
    except Exception as e:
        print(f"截图失败: {str(e)}")
        return False

def update_status(has_change):
    global is_active, last_activity_time
    current_time = time.time()
    idle_time = current_time - last_activity_time

    if has_change:
        if not is_active:
            log_status("开工")
        is_active = True
        last_activity_time = current_time  # 仅在有实际变化时更新时间
    else:
        if is_active and idle_time > INACTIVITY_THRESHOLD:
            log_status("未开工")
            is_active = False
        elif not is_active:
            pass

def main():
    global is_active, last_activity_time
    log_status("脚本启动")
    print(f"监控已开始，日志文件路径：{LOG_FILE}")
    
    is_active = True
    last_activity_time = time.time()
    log_status("开工")
    
    try:
        while True:
            has_change = check_screen_change()
            update_status(has_change)
            time.sleep(CHECK_INTERVAL)
    except KeyboardInterrupt:
        log_status("未开工")
        log_status("脚本手动停止")
    except Exception as e:
        log_status(f"脚本异常终止: {str(e)}")

if __name__ == "__main__":
    main()
